package org.shunya.duplicatefileperquisitor.searchengine;

import org.shunya.duplicatefileperquisitor.DuplicateFilePerquisitorObservable;
import org.shunya.duplicatefileperquisitor.gui.FileScanningService;
import org.shunya.duplicatefileperquisitor.model.File;
import org.shunya.duplicatefileperquisitor.model.FileGuiAttributes;
import org.shunya.duplicatefileperquisitor.model.FileType;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;

public class SearchEngine {

    private final Map<Long,File> allFiles = new LinkedHashMap<>();
    private final Set<File> originalFiles = new HashSet<>();
    private final List<File> duplicateFiles = new LinkedList<>();
    private final Set<Path> pathsTraversed = new HashSet<>();
    private final DuplicateFilePerquisitorObservable observable = new DuplicateFilePerquisitorObservable();
    private final FileGuiAttributes guiAttributes = new FileGuiAttributes(0, "");
    private int allFilesCount = 0;

    public SearchEngine(Observer observer) {
        observable.addObserver(observer);
    }

    public List<File> findDuplicateFiles(Set<Path> includedPaths, Set<Path> excludedPaths) throws IOException {
        for (Path includedPath : includedPaths) {
            allFilesCount += includedPath.toFile().list().length;
            walkFileTree(includedPath, excludedPaths);
        }
        Collections.sort(duplicateFiles);
        return duplicateFiles;
    }

    public Map<Long, File> getAllFiles() {
        return allFiles;
    }

    private void walkFileTree(Path startPath, Set<Path> excludedPaths) throws IOException {
        Files.walkFileTree(startPath, new CustomSimpleFileVisitor(observable, guiAttributes, allFiles, originalFiles, duplicateFiles, excludedPaths, pathsTraversed, EnumSet.allOf(FileType.class)));
    }

    public int getAllFilesCount() {
        return allFilesCount;
    }
}
